<template>
    <div>
        <el-container direction="vertical">
            <!-- 饼状图统计 -->
            <el-row type="flex" :gutter="20" justify="space-between">
                <!-- 账户统计 -->
                <el-col :span="8" v-if="baseStatisticsData.account">
                    <el-card :body-style="{height: '200px'}" shadow="hover">
                        <div slot="header" class="clearfix">
                            <span class="header-span">账户统计</span>
                        </div>
                        <el-row>
                            <el-col :span="12">
                                <el-form ref="accountStatisticsForm" label-position="right" label-width="auto">
                                    <el-row>
                                        <el-col>
                                            <el-form-item label="总用户：">
                                                <span style="font-weight: bold">{{baseStatisticsData.account.total}} 名</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col>
                                            <el-form-item label="现激活账户：">
                                                <span style="font-weight: bold">{{baseStatisticsData.account.total - baseStatisticsData.account.disable}} 名</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col>
                                            <el-form-item label="管理员：">
                                                <span style="font-weight: bold">{{baseStatisticsData.account.manager}} 名</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col>
                                            <el-form-item label="最新注册：" :inline-message="true">
                                                <span style="font-weight: bold">{{baseStatisticsData.account.lastRegisterDate}}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                </el-form>
                            </el-col>
                            <el-col :span="12">
                                <div id="accountChart" style="width: 100%;height: 200px"></div>
                            </el-col>
                        </el-row>
                    </el-card>
                </el-col>
                <!-- 区域统计 -->
                <el-col :span="8" v-if="baseStatisticsData.area">
                    <el-card :body-style="{height: '200px'}" shadow="hover">
                        <div slot="header" class="clearfix">
                            <span class="header-span">区域统计</span>
                        </div>
                        <el-row>
                            <el-col :span="12">
                                <el-form ref="areaStatisticsForm" label-position="right" label-width="auto">
                                    <el-row>
                                        <el-col>
                                            <el-form-item label="总布置区域：">
                                                <span style="font-weight: bold">{{baseStatisticsData.area.total}} 处</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col>
                                            <el-form-item label="当前激活区域：">
                                                <span style="font-weight: bold">{{baseStatisticsData.area.total - baseStatisticsData.area.disable}} 处</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col>
                                            <el-form-item label="区域最多部署：">
                                                <span style="font-weight: bold">{{baseStatisticsData.area.mostDeploy}} 台设备</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col>
                                            <el-form-item label="最新区域：">
                                                <span style="font-weight: bold">{{lastCreateAreaName}}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                </el-form>
                            </el-col>
                            <el-col :span="12">
                                <div id="areaChart" style="width: 100%;height: 200px"></div>
                            </el-col>
                        </el-row>
                    </el-card>
                </el-col>
                <!-- 设备统计 -->
                <el-col :span="8" v-if="baseStatisticsData.equipment">
                    <el-card :body-style="{height: '200px'}" shadow="hover">
                        <div slot="header" class="clearfix">
                            <span class="header-span">设备统计</span>
                        </div>
                        <el-row>
                            <el-col :span="12">
                                <el-form ref="equipmentStatisticsForm" label-position="right" label-width="auto">
                                    <el-row>
                                        <el-col>
                                            <el-form-item label="总部署设备：">
                                                <span style="font-weight: bold">{{baseStatisticsData.equipment.total}} 台</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col>
                                            <el-form-item label="已激活设备：">
                                                <span style="font-weight: bold">{{baseStatisticsData.equipment.total - baseStatisticsData.equipment.disable}} 台</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col>
                                            <el-form-item label="已收录数据：">
                                                <span style="font-weight: bold">{{baseStatisticsData.equipment.totalData}} 条</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col>
                                            <el-form-item label="危险数据：">
                                                <span style="font-weight: bold;color: #e05e5e">{{baseStatisticsData.equipment.alert}} 条</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                </el-form>
                            </el-col>
                            <el-col :span="12">
                                <div id="equipmentChart" style="width: 100%;height: 200px"></div>
                            </el-col>
                        </el-row>
                    </el-card>
                </el-col>
            </el-row>
            <!-- 折线图统计 -->
            <el-row type="flex">
                <el-col :span="24">
                    <el-card :body-style="{height: this.lineChartHeight}" shadow="hover">
                        <div slot="header" class="clearfix">
                            <el-row type="flex">
                                <!-- 卡片框Title -->
                                <el-col :span="12">
                                    <span class="header-span">数据统计</span>
                                </el-col>
                                <el-col :span="12">
                                    <!-- 时间跨度切换 -->
                                    <div style="float: right;margin-left: 20px">
                                        <el-dropdown trigger="click" @command="timeHandleCommand">
                                            <span class="el-dropdown-link">
                                                <span>{{timeUnit}}</span>
                                                <i class="el-icon-arrow-down el-icon--right"></i>
                                            </span>
                                            <el-dropdown-menu slot="dropdown" >
                                                <el-dropdown-item command="one_year">近1年</el-dropdown-item>
                                                <el-dropdown-item command="six_month">近6个月</el-dropdown-item>
                                                <el-dropdown-item command="three_month">近90天</el-dropdown-item>
                                                <el-dropdown-item command="one_month">近30天</el-dropdown-item>
                                                <el-dropdown-item command="one_week">近7天</el-dropdown-item>
                                            </el-dropdown-menu>
                                        </el-dropdown>
                                    </div>
                                    <!-- 显示单位切换 -->
                                    <div style="float: right">
                                        <span :class="dataUnit==='α粒子'?'el-span-active':'el-span-wait'" @click="dataHandleCommand('alpha')">α粒子</span>
                                        <span :class="dataUnit==='β粒子'?'el-span-active':'el-span-wait'" @click="dataHandleCommand('beta')">β粒子</span>
                                        <span :class="dataUnit==='γ射线'?'el-span-active':'el-span-wait'" @click="dataHandleCommand('gamma')">γ射线</span>
                                        <span :class="dataUnit==='空气湿度'?'el-span-active':'el-span-wait'" @click="dataHandleCommand('humidity')">空气湿度</span>
                                        <span :class="dataUnit==='温度'?'el-span-active':'el-span-wait'" @click="dataHandleCommand('temperature')">温度</span>
                                        <span :class="dataUnit==='风力'?'el-span-active':'el-span-wait'" @click="dataHandleCommand('windForce')">风力</span>
                                    </div>
                                </el-col>
                            </el-row>
                        </div>
                        <el-row>
                            <el-col :span="24">
                                <div id="radiationChart" :style="{height:this.lineChartHeight}" />
                            </el-col>
                        </el-row>
                    </el-card>
                </el-col>
            </el-row>
        </el-container>
    </div>
</template>

<script>
import * as echarts from 'echarts'
import {mapState,mapActions} from "vuex";

export default {
    name: "DataStatistics",
    props: {
        resizeSignal: {
            require: true
        }
    },
    data() {
        return {
            lineChartHeight: '',
            timeUnit: "近半年",
            dataUnit: "α粒子",
            accountChart: null,
            areaChart: null,
            equipmentChart: null,
            radiationChart: null,
        }
    },
    methods: {
        ...mapActions([
            'getBaseStatisticsData',
            'getStatisticsData'
        ]),
        getLineChartHeight() {
            this.lineChartHeight = window.innerHeight - 60 - (20 + 20) - (14 + 10) - (40 + 15) - (26 + 10 + 300 + 10) - 72 + 'px';
        },
        getSelectedData() {
            switch (this.dataUnit) {
                case 'α粒子':
                    return this.statisticsData.data.alpha;
                case 'β粒子':
                    return this.statisticsData.data.beta;
                case 'γ射线':
                    return this.statisticsData.data.gamma;
                case '空气湿度':
                    return this.statisticsData.data.humidity;
                case '温度':
                    return this.statisticsData.data.temperature;
                case '风力':
                    return this.statisticsData.data.windForce;
            }
        },
        getMarkLine(){
            let markline = {
                symbol: ['none', 'arrow'],
                label: {show: true},
                data: [
                    {
                        yAxis: 0.2,
                        lineStyle: {
                            type: 'dashed',
                            width: 1,
                            color: '#68c176',
                            opacity: 1
                        },
                        label: {
                            formatter: '健康阈值（0.2）'
                        }
                    },
                    {
                        yAxis: 0.5,
                        lineStyle: {
                            type: 'dashed',
                            width: 1,
                            color: '#ff8029cc',
                            opacity: 1
                        },
                        label: {
                            formatter: '安全阈值（0.5）'
                        }
                    },
                    {
                        yAxis: 0.7,
                        lineStyle: {
                            type: 'dashed',
                            width: 1,
                            color: '#ee6666',
                            opacity: 1
                        },
                        label: {
                            formatter: '危险阈值（0.7）'
                        }
                    }
                ]
            };

            //根据当前选择的dataUnit配置相应的MarkLine
            switch (this.dataUnit){
                case 'α粒子':{
                    return markline;
                }
                case 'β粒子':{
                    markline.data[0].yAxis = 0.1;
                    markline.data[0].label.formatter = '健康阈值（0.1）';
                    markline.data[1].yAxis = 0.3;
                    markline.data[1].label.formatter = '安全阈值（0.3）';
                    markline.data[2].yAxis = 0.45;
                    markline.data[2].label.formatter = '危险阈值（0.45）';
                    return markline;
                }
                case 'γ射线':{
                    markline.data[0].yAxis = 0.1;
                    markline.data[0].label.formatter = '健康阈值（0.1）';
                    markline.data[1].yAxis = 0.25;
                    markline.data[1].label.formatter = '安全阈值（0.25）';
                    markline.data[2].yAxis = 0.3;
                    markline.data[2].label.formatter = '危险阈值（0.3）';
                    return markline;
                }
                case '空气湿度':{
                    markline.data[0].lineStyle.opacity = 0;
                    markline.data[1].yAxis = 40;
                    markline.data[1].label.formatter = '干燥（40%）';
                    markline.data[2].yAxis = 80;
                    markline.data[2].label.formatter = '潮湿（80%）';
                    return markline;
                }
                case '温度':{
                    markline.data[0].lineStyle.opacity = 0;
                    markline.data[1].lineStyle.opacity = 0;
                    markline.data[2].lineStyle.opacity = 0;
                    return markline;
                }
                case '风力':{
                    markline.data[0].lineStyle.opacity = 0;
                    markline.data[1].lineStyle.opacity = 0;
                    markline.data[2].lineStyle.opacity = 0;
                    return markline;
                }
            }
        },
        dataHandleCommand(command) {
            if (command === 'alpha' && this.dataUnit !== 'α粒子') {
                this.dataUnit = 'α粒子';
            } else if (command === 'beta' && this.dataUnit !== 'β粒子') {
                this.dataUnit = 'β粒子';
            } else if (command === 'gamma' && this.dataUnit !== 'γ射线') {
                this.dataUnit = 'γ射线';
            } else if (command === 'temperature' && this.dataUnit !== '温度') {
                this.dataUnit = '温度';
            } else if (command === 'humidity' && this.dataUnit !== '空气湿度') {
                this.dataUnit = '空气湿度';
            } else if (command === 'windForce' && this.dataUnit !== '风力') {
                this.dataUnit = '风力';
            }
        },
        timeHandleCommand(command) {
            if (command === 'one_year' && this.timeUnit !== '近一年') {
                this.timeUnit = '近一年';
                this.getStatisticsData(0);
            } else if (command === 'six_month' && this.timeUnit !== '近半年') {
                this.timeUnit = '近半年';
                this.getStatisticsData(1);
            } else if (command === 'three_month' && this.timeUnit !== '近90天') {
                this.timeUnit = '近90天';
                this.getStatisticsData(2);
            } else if (command === 'one_month' && this.timeUnit !== '近30天') {
                this.timeUnit = '近30天';
                this.getStatisticsData(3);
            } else if (command === 'one_week' && this.timeUnit !== '近7天') {
                this.timeUnit = '近7天';
                this.getStatisticsData(4);
            }
        },
        initAccountChart() {
            let _this = this;
            //获取目标DOM
            let accountDiv = document.getElementById("accountChart");
            //初始化目标DOM
            this.accountChart = echarts.init(accountDiv);
            //先清空图表(为了那个加载动画效果)
            this.accountChart.clear();
            //配置图表
            this.accountChart.setOption({
                tooltip: {
                    trigger: 'item',
                    // formatter: '{a} <br/>{b}: {c} ({d}%)',
                    formatter: function (params) {
                        return params.data.name + '：' + params.data.value + " (" + params.percent + "%)"
                    }
                },
                series: [
                    {
                        name: '平台账户',
                        type: 'pie',
                        radius: ['30%', '90%'],
                        avoidLabelOverlap: false,
                        itemStyle: {
                            borderRadius: 3,
                            borderColor: '#fff',
                            borderWidth: 2
                        },
                        label: {
                            show: false
                        },
                        labelLine: {
                            show: false
                        },
                        data: [
                            {value: this.baseStatisticsData.account.disable, name: '禁用账户'},
                            {value: this.baseStatisticsData.account.manager, name: '管理员账户'},
                            {value: this.baseStatisticsData.account.active, name: '活跃账户'},
                            {value: this.baseStatisticsData.account.inactive, name: '非活跃账户'},
                        ]
                    }
                ],
                color: [
                    '#6a6c6e',
                    '#5470c6',
                    '#91cc75',
                    '#ee6666'
                ]
            });
            //绑定页面宽高变动事件,重新制定图表宽高
            window.addEventListener("resize", function () {
                _this.accountChart.resize()
            });
        },
        initAreaChart() {
            let _this = this;
            //获取目标DOM
            let areaDiv = document.getElementById("areaChart");
            //初始化目标DOM
            this.areaChart = echarts.init(areaDiv);
            //先清空图表(为了那个加载动画效果)
            this.areaChart.clear();
            //配置图表
            this.areaChart.setOption({
                tooltip: {
                    trigger: 'item',
                    formatter: function (params) {
                        return params.data.name + '：部署 ' + params.data.value + " 台 (" + params.percent + "%)";
                    }
                },
                series: [
                    {
                        name: '管理区域',
                        type: 'pie',
                        radius: ['30%', '90%'],
                        avoidLabelOverlap: false,
                        itemStyle: {
                            borderRadius: 3,
                            borderColor: '#fff',
                            borderWidth: 2
                        },
                        label: {
                            show: false
                        },
                        labelLine: {
                            show: false
                        },
                        data: this.baseStatisticsData.area ? this.baseStatisticsData.area.deployCountList : []
                    }
                ],
                color: [
                    '#6a6c6e',
                    '#5470c6',
                    '#91cc75',
                    '#fac858',
                    '#ee6666',
                    '#73c0de',
                    '#3ba272',
                    '#fc8452',
                    '#9a60b4',
                    '#ea7ccc'
                ]
            });
            //绑定页面宽高变动事件,重新制定图表宽高
            window.addEventListener("resize", function () {
                _this.areaChart.resize()
            });
        },
        initEquipmentChart() {
            let _this = this;
            //获取目标DOM
            let equipmentDiv = document.getElementById("equipmentChart");
            //初始化目标DOM
            this.equipmentChart = echarts.init(equipmentDiv);
            //先清空图表(为了那个加载动画效果)
            this.equipmentChart.clear();
            //配置图表
            this.equipmentChart.setOption({
                tooltip: {
                    trigger: 'item',
                    formatter: function (params) {
                        return params.data.name + '：' + params.data.value + " 台 (" + params.percent + "%)";
                    }
                },
                series: [
                    {
                        name: '管理区域',
                        type: 'pie',
                        radius: ['30%', '90%'],
                        avoidLabelOverlap: false,
                        itemStyle: {
                            borderRadius: 3,
                            borderColor: '#fff',
                            borderWidth: 2
                        },
                        label: {
                            show: false
                        },
                        labelLine: {
                            show: false
                        },
                        data: [
                            {value: this.baseStatisticsData.equipment.disable, name: '非激活设备'},
                            {value: this.baseStatisticsData.equipment.normal, name: '连接状态:正常'},
                            {value: this.baseStatisticsData.equipment.lag, name: '连接状态:延迟'},
                            {value: this.baseStatisticsData.equipment.disconnect, name: '连接状态:断开'}
                        ]
                    }
                ],
                color: [
                    '#6a6c6e',
                    '#91cc75',
                    '#fac858',
                    '#ee6666'
                ]
            });
            //绑定页面宽高变动事件,重新制定图表宽高
            window.addEventListener("resize", function () {
                _this.equipmentChart.resize()
            });
        },
        initRadiationChart() {
            let _this = this;
            //获取目标DOM
            let dataDiv = document.getElementById("radiationChart");
            //如果是重复加载,则先摧毁原有图表
            if (null !== this.radiationChart) {
                this.radiationChart.dispose();
            }
            //初始化目标DOM
            this.radiationChart = echarts.init(dataDiv);
            //title,用于无数据时的显示内容控制
            const title = {
                text: this.statisticsData.xAxis.length > 0 ? "" : "暂无数据",
                x: 'center',
                y: 'center',
                textStyle: {
                    color: '#65ABE7',
                    fontWeight: 'normal',
                    fontSize: 16
                }
            };
            //配置Option
            const seriesList = [];
            //获取选中单位的数据
            const selectedData = this.getSelectedData();
            //根据当前选择的dataUnit配置相应的MarkLine
            let markLine = this.getMarkLine();
            //计数器,用于区分每条线所代表的区域名称在statisticsData.areaName中的下标
            let nameIndex = 0;
            //生成seriesList[]
            echarts.util.each(selectedData.data, function (areaData) {
                seriesList.push({
                    type: 'line',
                    //线段样式
                    lineStyle: {
                        width: 2
                    },
                    //是否显示折线的结点
                    showSymbol: false,
                    name: _this.statisticsData.areaName[nameIndex++],
                    //图标末端每条线的名称显示
                    endLabel: {
                        show: true,
                        fontSize: 13,
                        fontWeight: 'bold',
                        formatter: function (params) {
                            return params.seriesName;
                        }
                    },
                    //图标末端每条线的名称之间的间隔
                    labelLayout: {
                        moveOverlap: 'shiftY'
                    },
                    //指针放在折线上,是否有突出显示
                    emphasis: {
                        focus: 'series'
                    },
                    //数据
                    data: areaData,
                    //区域标记线
                    markLine: markLine
                })
            })

            const option = {
                //Title
                title: title,
                //动画时间
                animationDuration: 2000,
                //数据提示框
                tooltip: {
                    //排序方式: 数据降序排列
                    order: 'valueDesc',
                    //触发方式: 指针指向折线
                    trigger: 'axis'
                },
                //x轴
                xAxis: {
                    //显示类型:离散(以天/周/月为单位)
                    type: 'category',
                    data: this.statisticsData.xAxis
                },
                //y轴
                yAxis: {
                    //轴线名称
                    name: selectedData.unit
                },
                //每条线的标记,未设置的均采用默认配置
                legend: {
                    left: 'center',
                    width: '85%'
                },
                //工具箱
                toolbox: {
                    show: true,
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        magicType: {type: ['line', 'bar']},
                    }
                },
                //图标中的绘图网格
                grid: {
                    //网格左侧离容器的距离
                    left: '4%',
                    //网格底部侧离容器的距离
                    bottom: '5%'
                },
                //线条(数据)
                series: seriesList
            }
            //应用配置
            this.radiationChart.setOption(option);
            //绑定页面宽高变动事件,重新制定图表宽高
            window.addEventListener("resize", function () {
                _this.radiationChart.resize()
            });
        },
        initChart() {
            //初始化统计图表
            this.initAccountChart();
            this.initAreaChart();
            this.initEquipmentChart();
            this.initRadiationChart();
        }
    },
    computed: {
        ...mapState({
            baseStatisticsData: state => state.active.baseStatisticsData,
            statisticsData: state => state.active.statisticsData,
            areaData: state => state.active.areaData
        }),
        lastCreateAreaName() {
            let name = this.areaData.find(item => item.areaId === this.baseStatisticsData.area.lastCreateAreaID);
            return name.areaName;
        }
    },
    created() {
        //绑定时间来适应窗口大小的变化,做到LineChart模块的高度自适应
        window.addEventListener("resize", this.getLineChartHeight, false);
        //获取适合当前页面的高度值
        this.getLineChartHeight();
    },
    mounted() {
        //获取统计数据
        this.getBaseStatisticsData();
        this.getStatisticsData(1);
    },
    watch: {
        resizeSignal(newValue, oldValue) {
            if (newValue) {
                //因为在DOM生成前图表就已经生成了,而此时的宽高值无法区分'px'和'%',因此通过在tab切换时传prop的方式来控制主动触发resize的时机
                window.dispatchEvent(new Event('resize'));
                //初始化
                this.initChart();
            }
        },
        dataUnit(newValue, oldValue) {
            if (newValue) {
                this.initRadiationChart();
            }
        },
        statisticsData(newValue, oldValue) {
            if (newValue) {
                this.initRadiationChart();
            }
        }
    }
}
</script>

<style scoped>
::v-deep .box-shadow{
    border: #e4e7ed solid 1px;
    box-shadow: 1px 1px 1px 0px #0000004d
}

::v-deep .el-row:first-child{
    margin-top: 0;
}

::v-deep .el-row{
    margin-top: 20px;
}

.el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
}

.el-icon-arrow-down {
    font-size: 12px;
}

.clearfix{
    font-size: 14px;
    font-weight: 500;
}

::v-deep .el-card__header{
    /*background-color: #ecf5ff;*/
    background-color: #fafafa;
}

.clearfix:before,
.clearfix:after{
    display: table;
    content: '';
}
.clearfix:after{
    clear: both;
}

::v-deep .el-form > .el-row{
    margin-top: 0;
}

::v-deep .el-row .el-form-item{
    margin-bottom: 10px;
}

::v-deep .el-span{
    cursor: pointer;
    color: #409EFF;
    font-size: 14px;
    margin-right: 10px;
}

::v-deep .el-span-active{
    font-size: 14px;
    cursor: default;
    margin-right: 10px;
}

::v-deep .el-span-wait{
    cursor: pointer;
    color: #409EFF;
    font-size: 14px;
    margin-right: 10px;
}

::v-deep .el-span-wait:hover{
    color: #1f5d97;
    -moz-transition:color 1s; /* Firefox 4 */
    -webkit-transition:color 1s; /* Safari and Chrome */
    -o-transition:color 1s; /* Opera */
}

::v-deep .el-card__header {
    /*background-color: #d4dbe7;*/
    background-color: #f7f7f7;
}

::v-deep .el-card__body{
    background-color: #fdfdfd;
}

.header-span{
    font-size: 14px;
    font-weight: bold;
    color: #303133;
}

</style>